#coding:utf-8

from django.http import HttpResponseRedirect, HttpResponse
from django.http import HttpResponseNotFound, HttpResponseForbidden, Http404
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User, Permission
from django.contrib.auth.models import Group as DjangoGroup
from django.contrib.auth.decorators import login_required, permission_required
from django.core.files.images import get_image_dimensions
from django.template import RequestContext

from auxiliaries import getGroupsForUser
from auxiliaries import getGroup
from auxiliaries import *

from auxiliaries import updateDictWithGeneralVars
from vle.vleApp.models import *
from vle.vleApp.models import Post, Thread
from vle.vleApp.models import Video, File

from info import getMyComments, updateStudentSesionHours, getStudentByUserID, getMyHomeworks
from form import EditFeedbackForm, UploadFileForm, RegisterForm, LoginForm
from form import TeacherRegistrationForm, ThreadCreationForm, PostCreationForm
from form import UploadVideoForm, UploadSyllabusForm, NewsCreationForm
from form import EditTeacherForm, EditStudentForm, EditGroupForm, SendHomeworkForm, SubjectsForm
from form import GroupExcelForm, RegisterGradesFileForm, PreferencesForm, UploadGradesForm

import datetime
import settings
import math
import os



SESSION_TIMER = 10 # time in seconds

def isWap(request):
    contentType =request.META.get('HTTP_ACCEPT','')
    if contentType:
        return contentType.find("application/vnd.wap.xhtml+xml") != -1
    return False

#!!!!!siempre es true porque isWap si existe, es una función y esta arriba ^
def response(html, dictionary):
    response= render_to_response(html, dictionary)
    if isWap:
        response['Content-Type'] = 'application/vnd.wap.xhtml+xml; charset=UTF-8'
    else:
        response['Content-Type'] = 'text/html; charset=UTF-8'
    return response

def start(request):
    return render_to_response('index.html',updateDictWithGeneralVars(request,{}))
    
################################################################################
#                                   FEEDBACK                                   #
################################################################################

@login_required(redirect_field_name='userLogin')
def retroGeneral(request, course, group):
    '''
    Receives a user ID, goes to DB and searches for that Student's
    quizzes and renders a page containing the average score of all of 
    them.
    
    '''

    courseModel = Course.objects.get(code=course)
    groupModel = Group.objects.get(Q(code=group),Q(course=courseModel))
    sessionTime = 0
    if request.user.groups.values()[0]['name'] == "Students":
        st = Student.objects.filter(username=request.user.username)[0]
        c = ConstantVariables.objects.filter(course = course, group = group)[0]
        avgHour = c.avgHour
        try:
            timeSessionComment = calcSessionTimeComment(sessionTime, avgHour, course, group)
        except:
            timeSessionComment = ""
        try:
            postComment = calcPostComment(request.user, course, group)
        except:
            postComment = ""
    generalComment = timeSessionComment + ". " + postComment

    return render_to_response('sessionTimeGrade.html',updateDictWithGeneralVars(request,{'name':request.user.username, "comment":generalComment, "group":groupModel, "course":courseModel, 'sessionHours':sessionTime}))

@login_required(redirect_field_name='userLogin')
def retroQuizzes(request, stname):
    '''
    Receives a Student name, goes to DB and searches for that Student's
    quizzes and renders a page containing the average score of all of 
    them.
    
    '''
    ansQuizList=[]
    gradeList=[]
    weekDayEnd = ConstantVariables.objects.all()[0].weekDayEnd
    print "weekdayEnd " + weekDayEnd
    if not weekDayEnd:
        weekDayEnd = 0
    try:
        st = Student.objects.get(name=stname)
        quizList = Quiz.objects.all()
        ansQuizList = AnsweredQuiz.objects.filter(student=st)
        for quiz in quizList:
            try:
                quizDate = quiz.date
                if inWeek(quizDate, weekDayEnd):
                    newGrade = AnsweredQuiz.objects.filter(student=st, quiz=quiz).grade
            except IndexError:
                newGrade=0
            gradeList.append(newGrade)
    except:
        pass
    
    average = lstAverage(gradeList)
    
    #This query is useful for any category, retrieves the appropiate
    #comment for certain grade 
    quizComment = getComment('quiz', average)
    return render_to_response('quizGrade.html',updateDictWithGeneralVars(request,{'stname':stname,
                                                  'average':average,
                                                  'comment':str(quizComment)}))
                                                  
@login_required(redirect_field_name='userLogin')
def retroForums(request, stname):
    listRatings=[]
    try:
        st = Student.objects.get(name=stname)
        listThreads = Thread.objects.all()
        for th in listThreads:
            try:
                newRating=Post.objects.filter(student=st,thread=th).order_by('-rating')[0].rating
            except IndexError:
                newRating=0
            listRatings.append(newRating)
    except:
        pass
    average=lstAverage(listRatings)
    average*=float(100/5)
    forumComment = getComment('forum',average)
    return render_to_response('quizGrade.html',{'stname':stname,
        'average':average, 'comment':str(forumComment)})
        

def deleteFeedbackComment(request,course, group, idFeedback):
    if request.user.is_authenticated():
        if request.user.groups.values()[0]['name'] == "Teachers":
            day = datetime.datetime.now()
            FeedbackComment.objects.filter(id=int(idFeedback)).delete()
            return HttpResponseRedirect('/retroalimentaciones/'+course+'/'+group+'/')
    else:
        return HttpResponseRedirect('/login/')

def deleteHomework(request,course, group, idHwk):
    if request.user.is_authenticated():
        if request.user.groups.values()[0]['name'] == "Teachers":
            day = datetime.datetime.now()
            Homework.objects.filter(id=int(idHwk)).delete()
            return HttpResponseRedirect('/tareas/'+course+'/'+group+'/')
    else:
        return HttpResponseRedirect('/login/')


#********************************ERRORES!!!*****************************************
@login_required(redirect_field_name='userLogin')
#@permission_required('change_feedbackcomment', login_url="/permissionDenied/")
def feedbackEdit(request, course, group):
    courseModel = Course.objects.get(code=course)
    groupModel = Group.objects.get(Q(code=group),Q(course=courseModel))
    day = datetime.datetime.now()
    if request.method == 'POST':
        form = EditFeedbackForm(request.POST)
        comentarios= FeedbackComment.objects.all()
        if form.is_valid():
            form.cleaned_data['comment1']
            form.cleaned_data['category1']
            form.cleaned_data['minGrade1']
            #form.cleaned_data['hourAverage1']
            feedbackList=[]
            if form['comment1'].data:
                feedbackList+=[form['comment1'].data]	
            if form['category1'].data:
                feedbackList+=[form['category1'].data]
            if form['minGrade1'].data:
                feedbackList+=[form['minGrade1'].data]
            #Saving in database                             
            feed=FeedbackComment(comment=feedbackList[0], category=feedbackList[1],minGrade=feedbackList[2] )
            feed.course = course
            feed.group = group
            feed.save()
            return HttpResponseRedirect('/retroalimentaciones/'+course+'/'+group+'/')
        else: 
            return render_to_response('feedbackEdit.html',updateDictWithGeneralVars(request,{"form":form,"mis_comentarios": getMyComments(course, group),"date":day, "course":courseModel , "group":groupModel}))
    else:
        return render_to_response('feedbackEdit.html', updateDictWithGeneralVars(request,{'form':EditFeedbackForm(),"mis_comentarios": getMyComments(course, group), "date":day, "course":courseModel , "group":groupModel}))


################################################################################
#                             NEWS/FEEDS                                                                                                                                                                #
################################################################################

def createNews(request,courseCode,groupCode):
    try:
        courseModel = Course.objects.get(code=courseCode)
        groupModel = Group.objects.get(Q(code=groupCode),Q(course=courseModel))
        filteredGroups = Group.objects.filter(teacher=request.user).exclude(id=groupModel.id)
    except:
        raise Http404

    if request.method == 'POST':
        form = NewsCreationForm(request.POST)
        form.fields['groups']._set_queryset(filteredGroups)

        if form.is_valid():
            news = form.save(commit=False)
            news.date=datetime.datetime.now()
            news.save()
            #The current group was excluded, then it should be added automatically
            form.save_m2m()
            news.groups.add(groupModel)
            return HttpResponseRedirect('/news/%s/%s/'%(courseCode,groupCode))
        else:
            return render_to_response('createNews.html', updateDictWithGeneralVars(request,{'form':form,"course": courseModel, "group":groupModel}))
    else:
        form = NewsCreationForm()
        form.fields['groups']._set_queryset(filteredGroups)
        
        
        return render_to_response('createNews.html', updateDictWithGeneralVars(request,{'form':form,"course": courseModel, "group":groupModel,"moreGroups":True if len(filteredGroups) else False}))

def news(request,courseCode,groupCode):
    try:
        courseModel = Course.objects.get(code=courseCode)
        groupModel = Group.objects.get(Q(code=groupCode),Q(course=courseModel))
        newsList = News.objects.filter(groups__code=groupCode).filter(groups__course=courseModel).order_by('-date')
    except:
        raise Http404

    return render_to_response('news.html',updateDictWithGeneralVars(request, {'newsList':newsList,'group':groupModel,'course':courseModel}))

def singleNews(request, newsID):
    try:
        newsList= [News.objects.get(id__exact=int(newsID))]
    except:
        raise Http404
    return render_to_response('news.html',updateDictWithGeneralVars(request, {'newsList':newsList}))
################################################################################
#                             FILES/VIDEOS                                     #
################################################################################


@permission_required('vleApp.add_file', login_url="/permissionDenied/")
@login_required(redirect_field_name='userLogin')
def uploadFile(request, courseCode, groupCode):
    try:
        courseModel = Course.objects.get(code=courseCode)
        groupModel = Group.objects.get(Q(code=groupCode),Q(course=courseModel))
    except:
        raise Http404
    
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            f = request.FILES['fileName']
            writeUploadedFile(f, 'static/files/')
            file = form.save(commit=False)
            file.filename = f
            file.date = datetime.datetime.now()
            file.save()
            if file.allGroups:
                groupsForCourseAndTeacher = Group.objects.filter(Q(course=courseModel),Q(teacher=request.user))
                for group in groupsForCourseAndTeacher: #getGroupsForUser(request.user):
                    file.groups.add(group)
            else:
                file.groups.add(groupModel)
            return HttpResponseRedirect('/course/%s/%s/'%(courseCode,groupCode))
    else:
        form = UploadFileForm()
    return render_to_response('uploadFile.html', updateDictWithGeneralVars(request,{'form': form,'course':courseModel,'group':groupModel}))

@permission_required('vleApp.add_file', login_url="/permissionDenied/")
@login_required(redirect_field_name='userLogin')
def uploadVideo(request,courseCode,groupCode):
    try:
        courseModel = Course.objects.get(code=courseCode)
        groupModel = Group.objects.get(Q(code=groupCode),Q(course=courseModel))
    except:
        raise Http404
    
    if request.method == 'POST':
        form = UploadVideoForm(request.POST, request.FILES)
        if form.is_valid():
            protected = False
            f = request.FILES['fileName']
            handleUploadedVideo(f)
            video = form.save(commit=False)
            video.filename = f
            video.date = datetime.datetime.now()
            if f.name.endswith(".flv"):
                thumbStr = str(f)[:-3] + 'png'
                video.thumbnail = thumbStr
                protected = video.protected
            else: #This means its an AVI file:
                #Avi files ar treated as Files, not as videos
                video = File(title=video.title,filename=f,description=video.description,date=video.date,allGroups=video.allGroups)


            video.save()
            if video.allGroups:
                groupsForCourseAndTeacher = Group.objects.filter(Q(course=courseModel),Q(teacher=request.user))
                for group in groupsForCourseAndTeacher: #getGroupsForUser(request.user):
                    video.groups.add(group)
            else:
                video.groups.add(groupModel)
            #form.save_m2m()
            if f.name.endswith('.avi'):
                handleAvi(f, video, protected)
            handleMpg(f,video)
            return HttpResponseRedirect('/course/%s/%s/'%(courseCode,groupCode))
    else:
        form = UploadVideoForm()
        #form.fields['group']._set_queryset(Group.objects.filter(teacher=request.user))
    return render_to_response('uploadVideo.html', updateDictWithGeneralVars(request,{'form': form,'course':courseModel,'group':groupModel}))

@login_required(redirect_field_name='userLogin')
def viewVideo(request,courseCode,groupCode,fileName):
    try:
        courseModel = Course.objects.get(code=courseCode)
        groupModel = Group.objects.get(Q(code=groupCode),Q(course=courseModel))
        videoModel = Video.objects.get(filename=fileName+'.flv')
    except:
        raise Http404
    return render_to_response('viewVideo.html',updateDictWithGeneralVars(request,{'group':groupModel,'course':courseModel,'fileName':fileName+'.flv','video':videoModel}))

@login_required(redirect_field_name='login')
def viewVideoMenu(request, courseCode, groupCode):
    ##VALIdate if user has access to this group
    try:
        lstQueryVideos = Video.objects.filter(groups__code=groupCode, groups__course__code=courseCode)
        courseModel=Course.objects.get(code=courseCode)
        groupModel= getGroup(courseModel,groupCode)
    except:
        raise Http404

    lstVideos=[]
    for v in lstQueryVideos:
        if File.objects.filter(filename=v.filename[:-3]+'avi'):
            lstVideos.append((v.title, v.description, v.filename, v.thumbnail,v.filename[:-3]+'avi',v.protected,v.id))
        else:
            lstVideos.append((v.title, v.description, v.filename, v.thumbnail,False,v.protected,v.id))
    returnVideos=[]
    numVideos=0
    for video in lstVideos:
        if numVideos%2==0:
            returnVideos.append([(video)])
            numVideos+=1
        else:
            returnVideos[-1].append(video)
            numVideos+=1

    
    return render_to_response('videoMenu.html',updateDictWithGeneralVars(request,{'lstVideos':returnVideos,'course':courseModel,'group':groupModel}))

@login_required(redirect_field_name='userLogin')
def fileMenu(request, courseCode, groupCode):
    lstFiles = File.objects.filter(groups__code=groupCode, groups__course__code=courseCode)
    lstFormats = ["doc","docx","ppt","pptx","xls","xlsx","mpp","pdf","txt","avi","rar","zip"]
    newList=[]
    for file in lstFiles:
        type=file.filename.split('.')[-1:][0]
        if type in lstFormats:
            if type in ["docx","pptx","xlsx"]:
                type=type[:-1]
            newList.append((file,type))
        else:
            newList.append((file,"generic"))
            
    courseModel=Course.objects.get(code=courseCode)
    groupModel= getGroup(courseModel,groupCode)
    return render_to_response('fileMenu.html',updateDictWithGeneralVars(request,{'lstFiles':newList,'course':courseModel,'group':groupModel}))

#path modifier fo template use.
# if you use: dir.dir.file dowloadFile will search for it in path/dir/dir/file
def downloadFile(request,pathModifier,filename):
    pathModifier=pathModifier.replace('.', '/')
    mimeTypeDict={'avi': 'video/x-msvideo',
                    'doc': 'application/msword',
                    'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                    'mpp': 'application/vnd.ms-project',
                    'pdf': 'application/pdf',
                    'ppt': 'application/mspowerpoint',
                    'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
                    'rar': 'application/x-rar-compressed',
                    'zip': 'application/x-compressed',
                    'xls': 'application/excel',
                    'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                    'generic': 'application/octet-stream'}

    type=filename.split('.')[-1:][0]

    filename=unicode(filename)
    path = os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
    filePath = "%s/%s/%s"%(path,pathModifier,filename)

    f = open(filePath)
    a = f.read()
    f.close()

    mType=mimeTypeDict.get(type,'generic')

    response= HttpResponse(a,mimetype=mType)
    response['Content-Type'] = "%s;charset='UTF-8'" % (mType)
    response['Content-Disposition'] = u'attachment; filename=%s'% (filename)
    return response

def deleteFile(request,fileId,courseCode,groupCode):
    try:
        fileModel=File.objects.get(id=fileId)
        groupModel=Group.objects.get(code=groupCode)
        fileTeacher=groupModel.teacher
    except:
        raise Http404


    if request.user.id==fileTeacher.id:
        fileModel.groups.remove(groupModel)
        fileModel.save()

        if len(fileModel.groups.values_list())==0:
            path= os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
            completeFilePath= "%s/files/%s" % (path,fileModel.filename)
            if os.path.isfile(completeFilePath):
                os.remove(completeFilePath)
            fileModel.delete()
        return HttpResponseRedirect('/fileMenu/%s/%s/'%(courseCode,groupCode))

    else:
        return HttpResponseRedirect('/permissionDenied/')

def deleteVideo(request,fileId,courseCode,groupCode):
    try:
        videoModel=Video.objects.get(id=fileId)
        groupModel=Group.objects.get(code=groupCode)
        fileTeacher=groupModel.teacher
    except:
        raise Http404


    if request.user.id==fileTeacher.id:
        videoModel.groups.remove(groupModel)
        videoModel.save()

        if len(videoModel.groups.values_list())==0:
            path= os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
            videoName=videoModel.filename[:-4]
            flvFilePath= "%s/videos/%s.flv" % (path,videoName)
            aviFilePath= "%s/files/%s.avi" % (path,videoName)
            mpgFilePath= "%s/videos/mobileVideos/%s.mpg" % (path,videoName)
            thumbFilePath= "%s/videos/thumbnails/%s.png" % (path,videoName)

            fileList=[flvFilePath, aviFilePath, mpgFilePath, thumbFilePath]

            for file in fileList:
                if os.path.isfile(file):
                    os.remove(file)
            videoModel.delete()

        return HttpResponseRedirect('/viewVideoMenu/%s/%s/'%(courseCode,groupCode))

    else:
        return HttpResponseRedirect('/permissionDenied/')

#-------------------------------------------------------
@login_required(redirect_field_name='userLogin')
def home(request):
    toDay = ((datetime.datetime.now()).ctime()).split(" ")[0]
    toMonth =((datetime.datetime.now()).ctime()).split(" ")[1]
    day = translateDay(toDay)
    month = translateMonth(toMonth)
    hour =((datetime.datetime.now()).ctime()).split(" ")[3]
    if ((datetime.datetime.now()).ctime()).split(" ")[2] == "":
        hour =((datetime.datetime.now()).ctime()).split(" ")[4]
    if hour.split(":")[0][0]=="0":
        hour2 = int(hour[1:2])
    else:
        hour2 = int(hour[0:2])
    mor = ""
    eve = ""
    nig = ""
    if hour2 <= 11 and hour2 > 5:
        mor = "OK"
    elif hour2 <= 18 and hour2 > 11:
        eve = "OK"
    elif hour2 <= 5 or hour2 > 18:
        nig = "OK"
    intDay = toMonth =((datetime.datetime.now()).ctime()).split(" ")[2]

    if not request.user.is_superuser:
        groupList=getGroupsForUser(request.user)
    else:
        groupList=[]
        
    newList=[]
    for group in groupList:
        newList.append([group,getGroupActivity(group.code,group.course.code,10)])

    print newList

    if request.user.groups.values().count() != 0:
        if request.user.groups.values()[0]['name'] == "Teachers" or request.user.groups.values()[0]['name'] == "Students":
            return render_to_response("home.html",updateDictWithGeneralVars(request,{"newList":newList,"day":day, "month":month, "intDay":intDay, "mor":mor, "eve":eve,"nig":nig }))
        else:
            return render_to_response("home.html",updateDictWithGeneralVars(request,{}))
    return render_to_response("home.html",updateDictWithGeneralVars(request,{"newList":newList,"day":day, "month":month, "intDay":intDay, "mor":mor, "eve":eve,"nig":nig }))

    
#-------------------------------------------------------

def sendHomework(request, courseCode, groupCode):
    courseModel=Course.objects.get(code=courseCode)
    groupModel= getGroup(courseModel,groupCode)
    if request.method == 'POST':
        if request.user.groups.values()[0]['name'] == "Teachers":
            form = SubjectsForm(request.POST)
            if form.is_valid():
                successBar = "Se ha agregado el asunto satisfactoriamente"
                t = form["subject"].data
                subject = Subject(text=t)
                subject.save()
                today = datetime.datetime.now()
                h = Homework(courseKey = courseCode, groupKey = groupCode, subjects = subject, date = today)
                h.save()
                #return HttpResponseRedirect('/course/%s/%s/'%(courseModel.code, groupModel.code))
                return render_to_response('sendHomework.html',updateDictWithGeneralVars(request,{'form':form,"tareas": getMyHomeworks(courseCode, groupCode), 'group':groupModel, 'course':courseModel}))
            else:
                return render_to_response('sendHomework.html',updateDictWithGeneralVars(request,{'form':form,"tareas": getMyHomeworks(courseCode, groupCode), 'group':groupModel, 'course':courseModel}))
        else:
            form = SendHomeworkForm(request.POST,request.FILES)
            if form.is_valid():

                filePath = os.path.join(os.path.dirname(__file__), 'static/mail/').replace('\\','/')
#                filePath = "%s\\mail\\"%(path)
                f=request.FILES['file']
                try:
                    writeUploadedFile(f,filePath)
                except:
                    return render_to_response('successMail.html',updateDictWithGeneralVars(request,{"successBar":"Hubo un error al enviar tu archivo. \n Verifica que tu archivo sea aceptado por el sistema"}))

                successBar = "Se ha enviado su tarea satisfactoriamente"
                subject = Subject.objects.filter(id = form["subjects"].data)[0].text
                message = form["text"].data
                attachment = "%s%s"%(filePath,f.name)
                sendEmailHomework(courseCode, groupCode, request.user.username, subject, message,request.user.email,attachment)
                return render_to_response('successMail.html',updateDictWithGeneralVars(request,{"successBar":successBar, 'group':groupModel, 'course':courseModel}))
            else:
                return render_to_response('sendHomework.html',updateDictWithGeneralVars(request,{'form':form, 'group':groupModel, 'course':courseModel}))
    else:
        if request.user.groups.values()[0]['name'] == "Teachers":
            form = SubjectsForm()
            return render_to_response('sendHomework.html',updateDictWithGeneralVars(request,{'form':form,"tareas": getMyHomeworks(courseCode, groupCode), 'group':groupModel, 'course':courseModel}))
        else:
            form = SendHomeworkForm()
            try:
                    h=Homework.objects.filter(courseKey = courseCode, groupKey = groupCode)
                    form.fields['subjects']._set_queryset(h)
            except:
                    h=["No hay tareas por ahora"]
                    form.fields['subjects']._set_queryset(h)
            return render_to_response('sendHomework.html',updateDictWithGeneralVars(request,{'form':form, 'group':groupModel, 'course':courseModel}))



loginHour="a"
def userLogin(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            loginText = request.POST.get('user', None)
            password = request.POST.get('password', None)
            user=authenticate(username=loginText,password=password)
            today = datetime.datetime.now()

            if user: 
                login(request, user)
                if ConstantVariables.objects.all().count() != 0:
                    weekDay = ConstantVariables.objects.all()[0].weekDayEnd
                    metric = ConstantVariables.objects.all()[0].metricDay
                else:
                    weekDay = str(today.month)+","+str(today.day-1)+","+str(getStrMonth(today.month))+","+str(today.year)
                    metric = 8
                if frontWeek(today, weekDay):
                    if ConstantVariables.objects.all().count() != 0:
                        c = ConstantVariables.objects.all()[0]
                        c.weekDayEnd = weekDays(weekDay, metric)
                        c.save()
                    else:
                       pass
                form.cleaned_data['user']
                form.cleaned_data['password']
                global loginHour
                loginHour = getHourTimeSession(datetime.datetime.now())
                request.session.set_expiry(0)

                return HttpResponseRedirect('/home/')
            else:
                return HttpResponseRedirect('/login/')
        else:
            return render_to_response('home.html',updateDictWithGeneralVars(request,{'es_wap':isWap(request), "form":form}))
    else:
        if request.user.is_authenticated():
                return HttpResponseRedirect('/home/')
                #return render_to_response('home.html', {'es_wap':isWap(request), 'name':request.user.get_full_name()})
        else:
                f = LoginForm()
                return render_to_response('home.html',updateDictWithGeneralVars(request,{'es_wap':isWap(request), "form":f}))


def uploadGrades(request,courseCode,groupCode):
    path = os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
    courseModel=Course.objects.get(code=courseCode)
    groupModel= getGroup(courseModel,groupCode)
    if request.method == 'POST':
        form = UploadGradesForm(request.POST, request.FILES)
        if form.is_valid():
            toDay = ((datetime.datetime.now()).ctime()).split(" ")[0]
            toMonth =((datetime.datetime.now()).ctime()).split(" ")[1]
            day = translateDay(toDay)
            month = translateMonth(toMonth)
            intDay = toMonth =((datetime.datetime.now()).ctime()).split(" ")[2]
            if intDay == "":
                intDay = toMonth =((datetime.datetime.now()).ctime()).split(" ")[3]
            lastDate = day + " " + intDay + " de " + month
            d = ConstantVariables.objects.filter(course = courseCode, group = groupCode)[0]
            d.lstDateUpGrades = lastDate
            d.save()
            filePath = "%s/grades/"%(path)
            fileName = "%s_%s" % (groupModel.teacher.username,courseModel.code)
            f=request.FILES['fileGrade']
            writeUploadedFile(f,filePath,"%s"%(fileName))
            return HttpResponseRedirect('/calificaciones/%s/%s/'%(courseModel.code,groupModel.code))
        else:
            return render_to_response('uploadGrades.html',updateDictWithGeneralVars(request,{'form':form,'group':groupModel,'course':courseModel}))
    else:
        form = UploadGradesForm()
        try:
            xlrd.open_workbook(path+"/grades/%s_%s.xls"%(groupModel.teacher.username,courseModel.code))
            hayCalificaciones=True
        except:
            hayCalificaciones=False
        return render_to_response('uploadGrades.html',updateDictWithGeneralVars(request,{'form':form,'hayCalificaciones':hayCalificaciones,'group':groupModel,'course':courseModel}))


@login_required(redirect_field_name='userLogin')
def editPreferences(request, course, group):
    if request.method == 'POST':
        form = PreferencesForm(request.POST, request.FILES)
        if form.is_valid():
            d = ConstantVariables.objects.filter(course = course, group = group)[0]
            d.avgHour = form["avgHour"].data
            d.metricDay = form["metricDay"].data
            d.startDate = form["startDay"].data
            d.hasStarted = False
            d.save()
            return render_to_response('registerVar.html',updateDictWithGeneralVars(request,{"successBar":"Sus preferencias han sido guardadas exitosamente", "form":form}))
        else:
            return render_to_response('registerVar.html',updateDictWithGeneralVars(request,{'es_wap':isWap(request), "form":form}))
    else:
        if request.user.is_authenticated():
            if request.user.groups.values().count() != 0:
                if request.user.groups.values()[0]['name'] == "Teachers":
                    f = PreferencesForm()
                    return render_to_response("registerVar.html",updateDictWithGeneralVars(request,{"form":f}))
                else:
                    return HttpResponseRedirect('/permissionDenied/')
            else:
                return HttpResponseRedirect('/home/')
        else:
            return HttpResponseRedirect('/login/')
                
#----------------------------------------------------------
@login_required(redirect_field_name='userLogin')
def checkSession(request):
    expiryTime = request.session.get_expiry_date()
    currentTime = datetime.datetime.now()
    if expiryTime <= currentTime:
	# this part of the if does not work yet
	return render_to_response('loggedOut.html', updateDictWithGeneralVars(request,{'es_wap':isWap(request)}))
    else:
	# expiryTime is being refreshed with every click
	return render_to_response('clickedSomething.html', updateDictWithGeneralVars(request,{'es_wap':isWap(request),
                            'expiryTime':expiryTime, 'currentTime':currentTime}))
	    
#----------------------------------------------------------
@login_required(redirect_field_name='userLogin')
def userLogout(request):
    logoutHour= getHourTimeSession(datetime.datetime.now())
    sessionHours = hourSubstraction(loginHour, logoutHour)
    #print dir(request.user)
    userID = request.user.id
    ##IF user is student
    #updateStudentSesionHours(userID, sessionHours)
    logout(request)
    f = LoginForm(request.POST)
    return HttpResponseRedirect('/login/')

#----------------Temporal --------------------
@login_required(redirect_field_name='userLogin')
#@permission_required(registrar alumno   ***no se el nombre del permission***)
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            ##Fill with all required fields first, if not on the form
            try:
                g = DjangoGroup.objects.get(name='Students')
            except:
                g = DjangoGroup(name='Students')
                g.save()
                g.permissions.add(Permission.objects.get(codename='add_video'), Permission.objects.get(codename='add_file'))

            now = datetime.datetime.now()
            #student = form.save(commit=False)
            #student.set_password(form['password'].data)
            #student.sesionTime = 0
            #student.save()
            
            student = Student(sesionTime=0)
            student.username = form["username"].data
            student.first_name = form["StName"].data
            student.last_name = form["LtName"].data
            student.email = form["email"].data

            if request.FILES:
                f = request.FILES['avatarFileName']
                writeUploadedFile(f,'static/resources/avatars/','%s'% (student.username))
                filePath="/resources/avatars/%s.%s" % (student.username,f.name.split('.')[-1])
            else:
                filePath="/resources/avatars/default_avatar.jpg"

            #get image dimensions
            path= os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
            completeFilePath= "%s/%s" % (path,filePath)
            (x,y)=get_image_dimensions(completeFilePath)
            newAvatar=Avatar()
            newAvatar.path=filePath
            newAvatar.width=x
            newAvatar.height=y
            newAvatar.save()
            student.avatar=newAvatar


            student.save()
            student.groups.add(g)  #Dice que student necesita primary key para una relacion muchos a muchos
            newPassword(form["username"].data)
            return render_to_response('createdAccount.html', updateDictWithGeneralVars(request,{'es_wap':isWap(request)}))
        else:
            return render_to_response('studentRegister.html',updateDictWithGeneralVars(request,{'es_wap':isWap(request), "form":form}))
    else:
        f = RegisterForm()
        return render_to_response('studentRegister.html',updateDictWithGeneralVars(request,{'es_wap':isWap(request), "form":f}))

@login_required(redirect_field_name='userLogin')
#@permission_required(registrar maestro ****no se el nombre del permission****)
def teacherRegistration(request):
    if request.method == 'POST':
        form = TeacherRegistrationForm(request.POST,request.FILES)
        if form.is_valid():
            ##Fill with all required fields first, if not on the form
            try:
                g = DjangoGroup.objects.get(name='Teachers')
            except:
                g = DjangoGroup(name='Teachers')
                g.save()
                g.permissions.add(Permission.objects.get(codename='add_video'),
                                  Permission.objects.get(codename='delete_video'),
                                    Permission.objects.get(codename='add_feedbackcomment'),
                                    Permission.objects.get(codename='change_feedbackcomment'),
                                    Permission.objects.get(codename='delete_feedbackcomment'),
                                    Permission.objects.get(codename='add_file'),
                                    Permission.objects.get(codename='delete_file'))

                g.save()
                
            teacher=form.save(commit=False)
            teacher.set_password(form['password'].data)

            if request.FILES:
                f = request.FILES['avatarFileName']
                writeUploadedFile(f,'static/resources/avatars/','%s'% (teacher.username))
                filePath="/resources/avatars/%s.%s" % (teacher.username,f.name.split('.')[-1])
            else:
                filePath="/resources/avatars/default_avatar.jpg"
            print filePath

            #get image dimensions
            path= os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
            completeFilePath= "%s/%s" % (path,filePath)
            (x,y)=get_image_dimensions(completeFilePath)
            newAvatar=Avatar()
            newAvatar.path=filePath
            newAvatar.width=x
            newAvatar.height=y
            newAvatar.save()
            teacher.avatar=newAvatar
            teacher.hasRegisteredVar = False

            teacher.save()
            form.save_m2m()
            teacher.groups.add(g)

            
            
            return render_to_response('successTeacher.html',updateDictWithGeneralVars(request,{}))
        else:
            return render_to_response('registrarMaestro.html',updateDictWithGeneralVars(request,{'form':form}))
    else:
        form = TeacherRegistrationForm()
        return render_to_response('registrarMaestro.html',updateDictWithGeneralVars(request,{'form':form}))

def editTeacherProfile(request):
    try:
        teacher=Teacher.objects.get(id=request.user.id)
    except:
        return HttpResponseRedirect('/permissionDenied/')

    avatarBig=resizeDimensionsH(teacher.avatar.width,teacher.avatar.height,100,True)
    avatarMed=resizeDimensionsH(teacher.avatar.width,teacher.avatar.height,50)
    
    if request.method == 'POST':
        form = EditTeacherForm(request.POST,request.FILES)
        if form.is_valid():
            teacher.first_name = form['first_name'].data
            teacher.last_name = form['last_name'].data
            teacher.email = form['email'].data
            teacher.location = form['location'].data
            teacher.phone_number = form['phone_number'].data
            teacher.messenger = form['messenger'].data
            teacher.skype = form['skype'].data
            teacher.homepage = form['homepage'].data


            if request.FILES:
                path= os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
            
                if teacher.avatar and (teacher.avatar.path.rfind("default_avatar") > -1):
                    completeFilePath= "%s%s" % (path,teacher.avatar.path)
                    print completeFilePath
                    if os.path.isfile(completeFilePath):
                        os.remove(completeFilePath)

                f = request.FILES['avatarFileName']
                writeUploadedFile(f,'static/resources/avatars/','%s'% (teacher.username))
                filePath="/resources/avatars/%s.%s" % (teacher.username,f.name.split('.')[-1])
                completeFilePath= "%s/%s" % (path,filePath)
                #get image dimensions
                (x,y)=get_image_dimensions(completeFilePath)
                teacher.avatar.path=filePath
                teacher.avatar.width=x
                teacher.avatar.height=y
                teacher.avatar.save()
                
            teacher.save()

            return HttpResponseRedirect('/home/')
        else:
            return render_to_response('editProfile.html',updateDictWithGeneralVars(request,{'form':form,'avatarBig':avatarBig,'avatarMed':avatarMed}))
    else:
        
        teacherData = {"first_name":teacher.first_name,
                        "last_name":teacher.last_name,
                        "email":teacher.email,
                        "location":teacher.location,
                        "phone_number":teacher.phone_number,
                        "messenger":teacher.messenger,
                        "skype":teacher.skype,
                        "homepage":teacher.homepage}
        form = EditTeacherForm(teacherData)

        

        return render_to_response('editProfile.html',updateDictWithGeneralVars(request,{'form':form,'avatarBig':avatarBig,'avatarMed':avatarMed}))

def editStudentProfile(request):
    try:
        student=Student.objects.get(id=request.user.id)
    except:
        return HttpResponseRedirect('/permissionDenied/')

    avatarBig=resizeDimensionsH(student.avatar.width,student.avatar.height,100,True)
    avatarMed=resizeDimensionsH(student.avatar.width,student.avatar.height,50)

    if request.method == 'POST':
        form = EditStudentForm(request.POST,request.FILES)
        if form.is_valid():
            student.first_name = form['first_name'].data
            student.last_name = form['last_name'].data
            student.email = form['email'].data
            student.phone_number = form['phone_number'].data
            student.messenger = form['messenger'].data
            student.skype = form['skype'].data
            student.twitter = form['twitter'].data


            if request.FILES:
                path= os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')

                if student.avatar and (student.avatar.path.rfind("default_avatar") > -1):
                    completeFilePath= "%s%s" % (path,student.avatar.path)
                    if os.path.isfile(completeFilePath):
                        os.remove(completeFilePath)

                f = request.FILES['avatarFileName']
                writeUploadedFile(f,'static/resources/avatars/','%s'% (student.username))
                filePath="/resources/avatars/%s.%s" % (student.username,f.name.split('.')[-1])
                completeFilePath= "%s/%s" % (path,filePath)
                #get image dimensions
                (x,y)=get_image_dimensions(completeFilePath)
                student.avatar.path=filePath
                student.avatar.width=x
                student.avatar.height=y
                student.avatar.save()

            student.save()

            return HttpResponseRedirect('/home/')
        else:
            return render_to_response('editProfile.html',updateDictWithGeneralVars(request,{'form':form,'avatarBig':avatarBig,'avatarMed':avatarMed}))
    else:

        studentData = {"first_name":student.first_name,
                        "last_name":student.last_name,
                        "email":student.email,
                        "phone_number":student.phone_number,
                        "messenger":student.messenger,
                        "skype":student.skype,
                        "twitter":student.twitter}
        form = EditStudentForm(studentData)



        return render_to_response('editProfile.html',updateDictWithGeneralVars(request,{'form':form,'avatarBig':avatarBig,'avatarMed':avatarMed}))

def permissionDenied(request):
    return render_to_response('permissionDenied.html',updateDictWithGeneralVars(request,{'returnPage':'/home/'}))

@login_required(redirect_field_name='userLogin')
#@permission_required('delete_feedbackcomment', login_url='userLogin')
def registerGroup(request):
    if request.method == "POST":
        form = GroupExcelForm(request.POST,request.FILES)
        if form.is_valid():
            newCourseKey = form['courseKey'].data
            newCourseName = form['courseName'].data
            newGroupKey = form['groupKey'].data
            f = request.FILES['fileName']
            
            path = os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
            fullPath=path+"/temp/"
            print '    -> f: '+fullPath+f.name
            
            writeUploadedFile(f,fullPath)
            teacher=Teacher.objects.get(id=request.user.id)
            regSt = registerStudents(f, newCourseKey, newCourseName, newGroupKey, teacher)
            if regSt == "error":
                message = "El grupo indicado pertenece a otro profesor."
                return render_to_response('registrarGrupo.html',updateDictWithGeneralVars(request,{'form':form, 'message':message}))
            return HttpResponseRedirect('/home/')
        else:
            return render_to_response('registrarGrupo.html',updateDictWithGeneralVars(request,{'form':form}))
    else:
        form = GroupExcelForm()

        return render_to_response('registrarGrupo.html',updateDictWithGeneralVars(request,{'form':form}))

def editGroup(request, courseCode, groupCode):
    try:
        courseModel=Course.objects.get(code=courseCode)
        groupModel=Group.objects.get(code=groupCode)
    except:
        raise Http404
    
    if request.method == "POST":
        form = EditGroupForm(request.POST,request.FILES)
        if form.is_valid():
            f = request.FILES['fileName']
            
            path = os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
            fullPath=path+"/temp/"
            print '    -> f: '+fullPath+f.name
            
            writeUploadedFile(f,fullPath)
            #writeUploadedFile(f,'static/temp/')
            if groupModel.teacher.id==request.user.id:
                teacher=Teacher.objects.get(id=request.user.id)
                regSt = registerStudents(f, courseModel.code, courseModel.name, groupModel.code, teacher)
                if regSt == "error":
                    message = "El grupo indicado pertenece a otro profesor."
                    return render_to_response('editGroup.html',updateDictWithGeneralVars(request,{'form':form, 'message':message}))
                    
            return HttpResponseRedirect('/course/%s/%s/'%(courseModel.code, groupModel.code))
        else:
            return render_to_response('editGroup.html',updateDictWithGeneralVars(request,{'form':form,'course':courseModel,'group':groupModel}))
    else:
        form = EditGroupForm()

        return render_to_response('editGroup.html',updateDictWithGeneralVars(request,{'form':form,'course':courseModel,'group':groupModel}))



def createThread(request, courseCode, groupCode):
    courseModel = Course.objects.get(code=courseCode)
    groupModel = getGroup(courseModel, groupCode)
    if request.method == 'POST':
        form = ThreadCreationForm(request.POST)

        if form.is_valid():
            #Validate professor owns this group:
            if not groupModel.teacher.username==request.user.username:
                return HttpResponseRedirect('/permissionDenied/')
            thread = form.save(commit=False)
            thread.date = datetime.datetime.now()
            thread.group = groupModel
            thread.save()
#            form.save_m2m()
            return render_to_response('forum.html',updateDictWithGeneralVars(request,{'title':thread.title,'description':thread.description,'threadList':getThreadsForGroup(groupModel),'course':courseModel,'group':groupModel,'messageBar':"Tema creado satisfactoriamente"}))
        else:
            return render_to_response('createThread.html',updateDictWithGeneralVars(request,{'form':form,'course':courseModel,'group':groupModel}))
    else:
        form = ThreadCreationForm()
        return render_to_response('createThread.html',updateDictWithGeneralVars(request,{'form':form,'course':courseModel,'group':groupModel}))


#-------------------------------------------------------------------------------
def viewCourses(request):

    userGroups = getGroupsForUser(request.user)
    return render_to_response('courseMenu.html',updateDictWithGeneralVars(request,{'groupList':userGroups}))

def courseHome(request, courseCode, groupCode):
    courseModel=Course.objects.get(code=courseCode)
    #try:
    groupModel= getGroup(courseModel,groupCode)
    userGroups = getGroupsForUser(request.user)
    toDay = ((datetime.datetime.now()).ctime()).split(" ")[0]
    toMonth =((datetime.datetime.now()).ctime()).split(" ")[1]
    day = translateDay(toDay)
    month = translateMonth(toMonth)
    intDay = toMonth =((datetime.datetime.now()).ctime()).split(" ")[2]
    if intDay == "":
        intDay = toMonth =((datetime.datetime.now()).ctime()).split(" ")[3]
    if groupModel in userGroups:
        width=groupModel.teacher.avatar.width
        height=groupModel.teacher.avatar.height
        (x,y)=resizeDimensionsH(width,height,100)
        forumActivityList=getForumActivity(groupCode,courseCode,5)
        fileVideoList=getAddedFilesAndVideos(groupCode,courseCode,5)
        newsList=getgroupNews(groupCode,courseCode,5)

        try:
            d = ConstantVariables.objects.filter(course = courseCode, group = groupCode)[0]
        except:
            if request.user.groups.values()[0]['name'] == "Teachers":
                list = ConstantVariables.objects.all()
                constList = []
                for item in list:
                    constList.append(item.id)
                if len(constList) != 0:
                    newID = max(constList)
                else:
                    newID = 1
                today = datetime.datetime.now()
                weekDay = str(today.month)+","+str(today.day)+","+str(getStrMonth(today.month))+","+str(today.year)
                c = ConstantVariables(newID+1,5,8,weekDays(weekDay,8),"/",toDay,"",False,request.user.id,courseCode,groupCode)
                c.save()
            else:
                return HttpResponseRedirect('/permissionDenied/')
        f = ConstantVariables.objects.filter(course = courseCode, group = groupCode)[0]
        if f.startDate == toDay and not f.hasStarted:
            today = datetime.datetime.now()
            weekDay = str(today.month)+","+str(today.day)+","+str(getStrMonth(today.month))+","+str(today.year)
            f = ConstantVariables.objects.filter(course = courseCode, group = groupCode)[0]
            f.weekDayEnd = weekDays(weekDay, f.metricDay)
            f.save()
            weekDayEnd=f.weekDayEnd.split(",")
            f.hasStarted = True
            f.save()
        if f.hasStarted:
            weekDayEnd=f.weekDayEnd.split(",")
        else:
            weekDayEnd=""
        lastDate = f.lstDateUpGrades
        return render_to_response('courseHome.html',updateDictWithGeneralVars(request,{'fileVideoActivity':fileVideoList,'forumActivity':forumActivityList,'newsList':newsList,'width':x,'height':y,'course':courseModel,'group':groupModel, 'weekDayEnd':weekDayEnd, "day":day, "month":month, "intDay":intDay, "lastDate":lastDate}))
    else:
            raise Http404
#except:
    #    return HttpResponseRedirect('/permissionDenied/')

def courseSyllabus(request, courseCode, groupCode):
    path= os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
    filePath= "%s/syllabus/" % (path)
    

    courseModel=Course.objects.get(code=courseCode)
    groupModel= getGroup(courseModel,groupCode)

    fileName="%s_%s.xls" %(groupModel.teacher.username,courseModel.code)

    try:
        lstSyllabus=getExcelRows(fileName,filePath)[1:]
        parsedList=[]

        for topic in lstSyllabus:
            topicNumber=str(topic[0].value)
            topicName=str(topic[1].value)
            topicDescription=""
            if topic[2].value:
                topicDescription=topic[2].value
            lstTopic=[topicNumber,range(len(topicNumber.split('.')[:-1])),topicName,topicDescription] #[number,indent,name,desc]

            parsedList.append(lstTopic)
            parsedList.sort()

        for topTuple in list(enumerate(parsedList)):
            idx = topTuple[0]
            parsedList[idx].append(True if idx%2==0 else False)

        retDict={'topicList':parsedList,'course':courseModel,'group':groupModel}

    except:
        retDict={'course':courseModel,'group':groupModel}

    return render_to_response('viewCourseSyllabus.html', updateDictWithGeneralVars(request,retDict))

def uploadSyllabus(request,courseCode,groupCode):

    courseModel=Course.objects.get(code=courseCode)
    groupModel= getGroup(courseModel,groupCode)

    path = os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')

    if request.method == 'POST':
        form = UploadSyllabusForm(request.POST,request.FILES)

        if form.is_valid():
            filePath = "%s/syllabus/"%(path)
            fileName = "%s_%s" % (groupModel.teacher.username,courseModel.code)
            f=request.FILES['fileName']
            writeUploadedFile(f,filePath,"%s"%(fileName))
            return HttpResponseRedirect('/temario/%s/%s/'%(courseModel.code,groupModel.code))
        else:
            return render_to_response('uploadSyllabus.html',updateDictWithGeneralVars(request,{'form':form,'group':groupModel,'course':courseModel}))
    else:
        form = UploadSyllabusForm()
        try:
            xlrd.open_workbook(path+"/syllabus/%s_%s.xls"%(groupModel.teacher.username,courseModel.code))
            hayTemario=True
        except:
            hayTemario=False
        return render_to_response('uploadSyllabus.html',updateDictWithGeneralVars(request,{'form':form,'hayTemario':hayTemario,'group':groupModel,'course':courseModel}))

def showThreads(request, courseCode, groupCode):
    courseModel = Course.objects.get(code=courseCode)
    try:
        groupModel = getGroup(courseModel,groupCode)
    except:
        return HttpResponseRedirect('/permissionDenied/')
    threadList = Thread.objects.filter(group=groupModel).order_by('-date')

    for thrd in threadList:
        postList=Post.objects.filter(thread=thrd).order_by('-date')
        thrd.postNumber=len(postList)
        try:
            thrd.lastPost=postList[0]
        except:
            pass

    return render_to_response('forum.html',updateDictWithGeneralVars
        (request,{'threadList':threadList,'group':groupModel,'course':courseModel}))

def showPosts(request, threadID):
    threadModel = Thread.objects.get(id=threadID)
    groupModel=threadModel.group
    courseModel=groupModel.course
    print threadModel
    
    postList = Post.objects.filter(thread=threadModel)
    postUserVoteList =[ ps for ps in PostUserVote.objects.filter(user=request.user) if ps.post.thread==threadModel]
    votedPostList =[ p.post for p in postUserVoteList ]
    for postItem in postList:
        try:
            avatar=postItem.creator.student.avatar

            print "student"
            print "avatar.wdith: %s"%(avatar.width)
            print  "avatar.hieght: %s"%(avatar.height)
        except:
            try:
                avatar=postItem.creator.teacher.avatar
                print "teacher"
                print "avatar.wdith: %s"%(avatar.width)
                print  "avatar.hieght: %s"%(avatar.height)
            except:
                pass
        (width,height)=resizeDimensionsWH(avatar.width,avatar.height,65,65,True,False)
        
        postItem.avatarWidth=width
        postItem.avatarHeight=height
        if postItem in votedPostList:
            vote = PostUserVote.objects.get(Q(post=postItem),Q(user=request.user)).voteType
            postItem.isVoted = True
            postItem.voteFavor = vote
            postItem.voteAgainst = not vote
        if postItem.creator == request.user:
            postItem.isMine = True
    
    return render_to_response('posts.html', updateDictWithGeneralVars(request, {'course':courseModel,'group':groupModel,'postList':postList,'thread':threadModel}))


def makePost(request, threadID, inReplyTo=""):

    threadID = int(threadID)
    threadModel = Thread.objects.get(id=threadID)
    groupModel=threadModel.group
    courseModel=groupModel.course
    if request.method == 'POST':
        form = PostCreationForm(request.POST)
        if form.is_valid():

            #Validate user can post in that thread:
            userGroups = getGroupsForUser(request.user)
            if not threadModel.group in userGroups:
                return HttpResponseRedirect('/permissionDenied/')
            post = form.save(commit=False)
            post.creator=request.user
            post.date = datetime.datetime.now()
            post.thread= threadModel
            post.rating=0
            post.save()
#            form.save_m2m()
            return HttpResponseRedirect('/thread/%s/'%(threadID))
        else:
            return render_to_response('createPost.html',updateDictWithGeneralVars(request,{'form':form,'course':courseModel,'group':groupModel,'course':courseModel,'thread':threadModel}))
    else:
        form = PostCreationForm()
        return render_to_response('createPost.html',updateDictWithGeneralVars(request,{'form':form,'course':courseModel,'group':groupModel,'thread':threadModel}))

def votePost(request, threadID,postID,type):
    postID=int(postID)
    type=bool(int(type))
    try:
        postModel = Post.objects.get(id=postID)
        validPost = True
        puv = PostUserVote.objects.filter(
                                                        Q(post=postModel),
                                                        Q(user=request.user)
                                                           )
        if puv:
            #user has already voted CHANGE THIS:
            return HttpResposeRedirect("/permissionDenied/")
    except:
        return HttpResponse("Cheater!!")

    puv =PostUserVote(post=postModel,user=request.user,voteType=type)
    puv.save()
    if validPost:
        postModel.rating = postModel.rating + (1 if type else -1)
        postModel.save()

    return HttpResponseRedirect("/thread/%s/"%(threadID))

@login_required(redirect_field_name='userLogin')
def grades(request, courseCode, groupCode):
    path= os.path.join(os.path.dirname(__file__), 'grades').replace('\\','/')
    
    courseModel=Course.objects.get(code=courseCode)
    groupModel= getGroup(courseModel,groupCode)
    fileName="%s_%s.xls" %(unicode(groupModel.teacher.username),unicode(courseModel.code))
    #d = ConstantVariables.objects.filter(course = courseCode, group = groupCode)[0]
    #fileName = d.gradesFile
    try:
        isTeacher = request.user.groups.values()[0]['name'] == "Teachers"
        j = getDisplayGrades(fileName, request.user.username, isTeacher, courseCode, groupCode)
        head = getExcelRow(fileName,0)
        head2=[]
        for item in head:
            head2.append(item.value)
        return render_to_response("grades.html",updateDictWithGeneralVars(request,{'calificaciones':j, 'header':head2,'course':courseModel,'group':groupModel}))
    except:
        return render_to_response('grades.html', updateDictWithGeneralVars(request,{'course':courseModel,'group':groupModel}))

def viewStudentsInGroup(request,courseCode,groupCode):
    courseModel=Course.objects.get(code=courseCode)
    groupModel=getGroup(courseModel, groupCode)
    studentList=Student.objects.filter(group=groupModel)
    stdList=[]
    for student in studentList:
        width=student.avatar.width
        height=student.avatar.height
        (width,height)=resizeDimensionsWH(width,height,50,50)
        stdList.append([student,width,height])

    return render_to_response("groupStudents.html",updateDictWithGeneralVars(request,{'studentList':stdList, 'course':courseModel,'group':groupModel}))


def teacherProfile(request,groupId):
    groupId=int(groupId)
    try:
        groupModel=Group.objects.get(id=groupId)
    except:
        raise Http404
    return render_to_response('profiles/teacherProfile.html',updateDictWithGeneralVars(request, {'group':groupModel}))

######################################################################
#                                 ADMIN                              #
######################################################################
def viewAllCourses(request):
    if not request.user.is_superuser:
        return HttpResponseRedirect('/permissionDenied/')

    courseList=Course.objects.all()
    grpList=[]
    for crse in courseList:
        groups=Group.objects.filter(course=crse)
        for group in groups:
            width=group.teacher.avatar.width
            height=group.teacher.avatar.height
            (x,y)=resizeDimensionsH(width,height,60,True)
            group.avatarWidth=x
            group.avatarHeight=y
            group.studentNumber=len(group.students.values_list())
        grpList.append([crse,groups])
    return render_to_response("admin/viewAllCourses.html",updateDictWithGeneralVars(request,{'grpList':grpList}))

def viewAllStudents(request,page,sort="unm"):
    #possible sorts: unm,fnm,lnm, mai
    pageLength=10

    page = int(page)
    
    if not request.user.is_superuser:
        return HttpResponseRedirect('/permissionDenied/')

    if sort=="fnm":
        studentList=Student.objects.all().order_by('first_name')
    elif sort=="lnm":
        studentList=Student.objects.all().order_by('last_name')
    elif sort=="mai":
        studentList=Student.objects.all().order_by('email')
    else:
        studentList=Student.objects.all().order_by('username')

    pageList=range(1,len(studentList[::pageLength])+1)
    studentList=studentList[(page-1)*pageLength:page*pageLength]

    for student in studentList:
        (width,height)=resizeDimensionsWH(student.avatar.width,student.avatar.height,50,50,False,True)
        student.avatarWidth=width
        student.avatarHeight=height

    return render_to_response("admin/viewAllStudents.html",updateDictWithGeneralVars(request,{'studentList':studentList,'pageList':pageList,'sort':sort}))

def viewAllTeachers(request,page,sort="unm"):
    pageLength=10

    page = int(page)

    if not request.user.is_superuser:
        return HttpResponseRedirect('/permissionDenied/')

    if sort=="fnm":
        teacherList=Teacher.objects.all().order_by('first_name')
    elif sort=="lnm":
        teacherList=Teacher.objects.all().order_by('last_name')
    elif sort=="mai":
        teacherList=Teacher.objects.all().order_by('email')
    else:
        teacherList=Teacher.objects.all().order_by('username')

    pageList=range(1,len(teacherList[::pageLength])+1)

    teacherList=teacherList[(page-1)*pageLength:page*pageLength]

    for teacher in teacherList:
        (width,height)=resizeDimensionsWH(teacher.avatar.width,teacher.avatar.height,50,50,False,True)
        teacher.avatarWidth=width
        teacher.avatarHeight=height
    
    return render_to_response("admin/viewAllTeachers.html",updateDictWithGeneralVars(request,{'teacherList':teacherList,'pageList':pageList,'sort':sort}))

######################################################################
#                                  MIDP                              #
######################################################################

def loginMobile(request):
    user = request.POST.get('user', None)
    password = request.POST.get('password', None)
    if user == None:
        user = "nobody"
	# Authenticate
    isValidUser = authenticate(username=user, password=password)	    
    if isValidUser:
        return respondToMobile(user)
    else:
        return respondToMobile('nobody')# The MIDP will handle this correctly
		
def listVideos(request):
    #MPG videos are located in: path/videos/mobileVideos with the same name as their flv counterparts
    user = request.POST.get('user', None)
    if user == None:
        user = "a00000000"
    userObject = User.objects.get(username=user)
    groups=getGroupsForUser(userObject) # request.user is an object and I only have the login
    #print "    GROUPS: "+" ".join(groups)
    videoList=[]
    for grp in groups:
        videoList.append([grp, Video.objects.filter(groups__in=[grp])])
    
    xml=""
    print len(videoList)
    for element in videoList:
        xml+="<group>"
        groupNumber = element[0].code
        groupName = element[0].course.name
        courseKey = element[0].course.code
        xml+="\n<name>%s - %s</name>" % (groupName, groupNumber)
        for video in element[1]:
            #url = "http://localhost:8000/videos/mobileVideos/gamma.mpg/"
            url = "http://localhost:8000/videos/mobileVideos/"+video.filename[:-4]+".mpg/"
            newVideo = "\n<video>\n<title>%s</title><description>%s</description><url>%s</url></video>" % (video.title,video.description,url)
            xml+= newVideo
        xml+="</group>"
        
    xml = "<videos>\n"+xml+"</videos>\n"
    print xml
    return respondToMobile(xml)
    
def listGroups(request):
    user = request.POST.get('user', None)
    if user == None:
        user = "nobody"
    userObject = User.objects.get(username=user)    
    groups=getGroupsForUser(userObject)
    xml = ""
    for grp in groups:
        xml += "<group>"+ grp.course.name+"::"+grp.code+"</group>"
    xml = "<groups>"+ xml +"</groups>"
    return respondToMobile(xml)
    
def listThreads(request):
    courseName = request.POST.get('course', None)
    group = request.POST.get('group', None) 
    courseModel = Course.objects.get(name=courseName)
    try:
        groupModel = getGroup(courseModel, group)
    except:
        print '     -> permissionDenied'
    threads = Thread.objects.filter(group=groupModel).order_by('-date')
    xml = ""
    for thread in threads:
        xml += "<thread>"+ thread.title +"</thread>"
    xml = "<threads>"+ xml +"</threads>"
    return respondToMobile(xml)
    
def listPosts(request):
    threadName = request.POST.get('thread', None)
    print "    -> "+threadName
    threadModel = Thread.objects.get(title=threadName)
    postList = Post.objects.filter(thread=threadModel)
    xml = ""
    for post in postList:
        xml += "<post><title>"+ post.title +"</title><content>"+post.content+"</content></post>"
    xml = "<posts>"+ xml +"</posts>"
    print "    -> posts\n"+xml
    return respondToMobile(xml)
